
function smartRepeat(str) {
  //指针
  let index = 0
  //栈1，用来存放数字
  let stack1 = []
  //栈2，用来存放临时字符
  let stack2 = []
  //剩余字符串
  let rest = str

  while (index < str.length - 1) {
    console.log(index, stack1, stack2, rest)

    //看剩余部分是否是以数字和[开头
    if (/^\d+\[/.test(rest)) {
      //取出数字
      let repeatCount = Number(rest.match(/^(\d+)\[/)[1])

      //数字压栈
      stack1.push(repeatCount)

      //空字符串压栈
      stack2.push('')

      //移动指针
      index += repeatCount.toString().length + 1
    } else if (/^\w+\]/.test(rest)) {
      //看剩余部分是否是以字符和]开头

      //取出需要重复的字符内容
      let word = rest.match(/^(\w+)\]/)[1]

      stack2[stack2.length - 1] = word

      //此处 指针 移动的 距离非常巧妙
      index += word.length
    } else {
      //如果不符合上面两种情况，则没有新的重复项了
      let repeatedChildStr = stack2.pop().repeat(stack1.pop())

      stack2[stack2.length - 1] += repeatedChildStr
      index++
    }

    //剩余部分
    rest = str.substring(index)
  }

  return stack2.pop().repeat(stack1.pop())
}

let str = '3[abc]'
let str2 = '3[2[a]2[b]]'
let str3 = '2[1[aa]3[bb]2[3[cc]4[dddd]]]'
console.log(smartRepeat(str))